<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { getHouseController, getBuildingController } from '@/api-client'
import type { HouseVO, HouseAddRequest, HouseQueryRequest, Building } from '@/api-client'

// 响应式数据
const loading = ref(false)
const tableData = ref<HouseVO[]>([])
const total = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const multipleSelection = ref<HouseVO[]>([])
const buildingList = ref<Building[]>([])

// 分页参数
const pagination = reactive({
  current: 1,
  pageSize: 10,
})

// 查询表单
const queryForm = reactive<HouseQueryRequest>({
  current: 1,
  pageSize: 10,
  numbers: '',
  storey: undefined,
  status: undefined,
  buildingId: undefined,
  intoDateStart: '',
  intoDateEnd: '',
  areaMin: undefined,
  areaMax: undefined,
  remarks: '',
})

// 新增/编辑表单
const houseForm = reactive<HouseAddRequest>({
  numbers: '',
  storey: undefined,
  status: 0,
  buildingId: undefined,
  intoDate: '',
  area: undefined,
  remarks: '',
})

// 当前编辑的房屋ID
const currentEditId = ref<number>()

// 房屋状态选项
const statusOptions = [
  { label: '空置', value: 0 },
  { label: '已入住', value: 1 },
]

// 表单验证规则
const rules = reactive<FormRules<HouseAddRequest>>({
  numbers: [
    { required: true, message: '请输入房间号码', trigger: 'blur' },
    { max: 50, message: '房间号码不能超过50个字符', trigger: 'blur' },
  ],
  storey: [
    { required: true, message: '请输入所在楼层', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '楼层必须在1-100之间', trigger: 'blur' },
  ],
  buildingId: [{ required: true, message: '请选择所属建筑', trigger: 'change' }],
  status: [{ required: true, message: '请选择房屋状态', trigger: 'change' }],
  area: [
    { type: 'number', min: 0, max: 1000, message: '面积必须在0-1000平方米之间', trigger: 'blur' },
  ],
  remarks: [{ max: 200, message: '房屋描述不能超过200个字符', trigger: 'blur' }],
})

// 状态显示
const getStatusText = (status: number | undefined) => {
  return status === 1 ? '已入住' : '空置'
}

const getStatusType = (status: number | undefined) => {
  return status === 1 ? 'success' : 'info'
}

// 获取建筑列表
const fetchBuildingList = async () => {
  try {
    const { getAllBuildings } = getBuildingController()
    const response = await getAllBuildings()
    if (response.data) {
      buildingList.value = response.data
    }
  } catch (error) {
    console.error('Error fetching building list:', error)
  }
}

// 获取房屋列表
const fetchHouseList = async () => {
  loading.value = true
  try {
    const { queryHouseByPage } = getHouseController()
    const response = await queryHouseByPage({
      ...queryForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    })

    console.log('House API Response:', response)

    if (response.data?.records) {
      tableData.value = response.data.records
      total.value = response.data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取房屋列表失败')
    console.error('Error fetching house list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchHouseList()
}

// 重置搜索
const handleReset = () => {
  queryForm.numbers = ''
  queryForm.storey = undefined
  queryForm.status = undefined
  queryForm.buildingId = undefined
  queryForm.intoDateStart = ''
  queryForm.intoDateEnd = ''
  queryForm.areaMin = undefined
  queryForm.areaMax = undefined
  queryForm.remarks = ''
  pagination.current = 1
  fetchHouseList()
}

// 分页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchHouseList()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchHouseList()
}

// 打开新增对话框
const handleAdd = () => {
  isEdit.value = false
  houseForm.numbers = ''
  houseForm.storey = undefined
  houseForm.status = 0
  houseForm.buildingId = undefined
  houseForm.intoDate = ''
  houseForm.area = undefined
  houseForm.remarks = ''
  currentEditId.value = undefined
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row: HouseVO) => {
  isEdit.value = true
  houseForm.numbers = row.numbers || ''
  houseForm.storey = row.storey
  houseForm.status = row.status || 0
  houseForm.buildingId = row.building?.id
  houseForm.intoDate = row.intoDate || ''
  houseForm.area = row.area
  houseForm.remarks = row.remarks || ''
  currentEditId.value = row.id
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const { addHouse, updateHouse } = getHouseController()

        if (isEdit.value && currentEditId.value) {
          await updateHouse(currentEditId.value, houseForm)
          ElMessage.success('编辑房屋成功')
        } else {
          await addHouse(houseForm)
          ElMessage.success('新增房屋成功')
        }

        dialogVisible.value = false
        fetchHouseList()
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑房屋失败' : '新增房屋失败')
        console.error('Error submitting form:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 取消对话框
const handleCancel = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 删除单个房屋
const handleDelete = async (row: HouseVO) => {
  if (!row.id) return

  try {
    await ElMessageBox.confirm(`确定要删除房屋"${row.numbers}"吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    loading.value = true
    const { deleteHouse } = getHouseController()
    await deleteHouse({ id: row.id })
    ElMessage.success('删除成功')
    fetchHouseList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('Error deleting house:', error)
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的房屋')
    return
  }

  const houseNumbers = multipleSelection.value.map((item) => item.numbers).join('、')

  try {
    await ElMessageBox.confirm(`确定要删除以下房屋吗？\n${houseNumbers}`, '确认批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    loading.value = true
    const ids = multipleSelection.value
      .map((item) => item.id)
      .filter((id): id is number => id !== undefined)

    const { deleteHouseBatch } = getHouseController()
    await deleteHouseBatch(ids)
    ElMessage.success('批量删除成功')
    fetchHouseList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('Error batch deleting houses:', error)
    }
  } finally {
    loading.value = false
  }
}

// 选择变化
const handleSelectionChange = (selection: HouseVO[]) => {
  multipleSelection.value = selection
}

// 页面加载时获取数据
onMounted(() => {
  fetchBuildingList()
  fetchHouseList()
})
</script>

<template>
  <div class="house-view">
    <div class="page-header">
      <h2>房屋管理</h2>
      <p>管理小区内的房屋信息，包括房间号、楼层、状态等</p>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="queryForm" inline class="search-form">
        <el-form-item label="房间号码">
          <el-input
            v-model="queryForm.numbers"
            placeholder="请输入房间号码"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="所在楼层">
          <el-input-number
            v-model="queryForm.storey"
            placeholder="楼层"
            :min="1"
            :max="100"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item label="房屋状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属建筑">
          <el-select
            v-model="queryForm.buildingId"
            placeholder="请选择建筑"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="building in buildingList"
              :key="building.id"
              :label="`${building.numbers} ${building.units}`"
              :value="building.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="面积范围">
          <div style="display: flex; align-items: center; gap: 8px">
            <el-input-number
              v-model="queryForm.areaMin"
              placeholder="最小面积"
              :min="0"
              style="width: 120px"
            />
            <span>-</span>
            <el-input-number
              v-model="queryForm.areaMax"
              placeholder="最大面积"
              :min="0"
              style="width: 120px"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"> 搜索 </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作区域 -->
    <div class="action-section">
      <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增房屋 </el-button>
      <el-button
        type="danger"
        :icon="Delete"
        :disabled="multipleSelection.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="numbers" label="房间号码" min-width="100" />
        <el-table-column prop="storey" label="所在楼层" width="100" />
        <el-table-column label="所属建筑" min-width="150">
          <template #default="{ row }">
            {{ row.building ? `${row.building.numbers} ${row.building.units}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="房屋状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="面积(㎡)" width="100" />
        <el-table-column prop="intoDate" label="入住时间" width="120" />
        <el-table-column prop="remarks" label="房屋描述" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑房屋' : '新增房屋'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="houseForm" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间号码" prop="numbers">
              <el-input
                v-model="houseForm.numbers"
                placeholder="请输入房间号码，如：101、102"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在楼层" prop="storey">
              <el-input-number
                v-model="houseForm.storey"
                placeholder="请输入楼层"
                :min="1"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属建筑" prop="buildingId">
              <el-select
                v-model="houseForm.buildingId"
                placeholder="请选择建筑"
                style="width: 100%"
              >
                <el-option
                  v-for="building in buildingList"
                  :key="building.id"
                  :label="`${building.numbers} ${building.units}`"
                  :value="building.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房屋状态" prop="status">
              <el-select v-model="houseForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房屋面积" prop="area">
              <el-input-number
                v-model="houseForm.area"
                placeholder="请输入面积"
                :min="0"
                :max="1000"
                :precision="2"
                style="width: 100%"
              />
              <span style="margin-left: 8px; color: #999">平方米</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入住时间" prop="intoDate">
              <el-date-picker
                v-model="houseForm.intoDate"
                type="date"
                placeholder="请选择入住时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="房屋描述" prop="remarks">
          <el-input
            v-model="houseForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入房屋描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit(formRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="css" scoped>
.house-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.action-section {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background-color: #fafafa;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>
